const Common = require('../controllers/common')
const Constant = require('../constant/constant')
const { JWT } = require('../utils/jwt')

function checkToken(req, res) {
  //1、创建一个返回值对象
  let resObj = Common.clone(Constant.DEFAULT_SUCCESS)
  //2、验证token，一般和前端约定把token放在请求头中
  let token = req.headers.token
  console.log(token)
  if (!token) {
    return res.send('请携带token')
  }
  let jwt = new JWT()
  //验证token的返回结果 1、false表示没登陆，2、checkRes = {}判断是否过期
  let checkRes = jwt.verify(token)
  console.log(checkRes)
  if (!checkRes) {
    resObj.code = 401
    resObj.msg = '请先登录'
    res.send(resObj)
    return false
  }
  console.log(checkRes)
  //1970到签发时间点的秒时间
  let signTime = checkRes.iat
  //1970到现在时间点的秒时间
  let now = Math.floor(Date.now() / 1000)
  //假定时间限制不能超1分钟
  if (now - signTime > 86400) {
    resObj.code = 402
    resObj.msg = '请重新登录'
    res.send(resObj)
    return false
  }
  return true
}

exports.checkToken = checkToken
